package task;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeSet;
import java.util.regex.Pattern;

import org.eclipse.swt.graphics.ImageData;

import util.JdbcUtil;


public class DistinctValues extends DbTask {
	

	@Override
	public void doRun(Map<String, String> props) throws SQLException {
		ArrayList<String> schemas = null;
		String schemaFilter = props.get("schemaFilter");
		String table = props.get("table");
		String column = props.get("column");
		String columnFilter = props.get("columnFilter");
		final TreeSet<String> values = new TreeSet<String>();
		schemas = ListAllShemasWithVersion.getSchemas(conn(), schemaFilter);
		final Pattern pattern = columnFilter==null ? null : Pattern.compile(columnFilter.toLowerCase());

		for (final String schema : schemas) {
			String sql2 = String.format("select distinct %s from %s.%s", column, schema, table);
			try {
				Traverser t = new Traverser(sql2) {

					@Override
					protected void visit(ResultSet rs) throws SQLException {
						String value = rs.getString(1);
						if (pattern == null || pattern.matcher(value.toLowerCase()).matches()) {
							values.add(schema + "." + value);
						}
					}
				};
			} catch (SQLException e) {
				System.err.printf("%s.%s.%s not found%n", schema, table, column);
			}
		}
		for (String s : values) {
			System.out.println(s);
		}
	}

	@Override
	public String getDescription() {
		String desc = "List all distinct selected column values from table, from all selected schemas\n" +
				" (regular expression schema-filter and/or value-filter may be provided)";
		return desc;
	}

	@Override
	public ImageData getImageData() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String[] propertyNames() {
		String[] props = { "schemaFilter", "table", "column", "columnFilter" };
		return props;
	}
}
